//
//  OAuthViewController.swift
//  Weibo
//
//  Created by 孙国强 on 2017/6/23.
//  Copyright © 2017年 孙国强. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupNavigationBar()
        
        loadPage()
    }

}

// MARK:- 设置UI界面
extension OAuthViewController {
    fileprivate func setupNavigationBar() {
        // 设置左侧的item
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(OAuthViewController.closeItemClick))
        
        // 设置右侧的item
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(OAuthViewController.fillItemClick))
        
        // 设置标题
        title = "登录页面"
    }
    
    fileprivate func loadPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
        
        guard let url = URL(string : urlString) else {
            return
        }
        
        let request = URLRequest(url: url)
        
        webView.loadRequest(request)
        
    }
}

// MARK:- 事件监听
extension OAuthViewController {
    @objc fileprivate func closeItemClick() {
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func fillItemClick() {
        let jsCode = "document.getElementById('userId').value='15088139474';document.getElementById('passwd').value='huangjiawenm520.';"
        
        webView.stringByEvaluatingJavaScript(from: jsCode)
        
    }
}

// MARK:- webView的delegate方法
extension OAuthViewController : UIWebViewDelegate {
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    // 当准备加载某一个页面时，会执行该方法
    // 返回值：true -> 继续加载页面 false -> 不会加载该页面
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 获取加载网页的url
        guard let url = request.url else {
            return true
        }
        
        // 获取URL中的字符串
        let urlString = url.absoluteString
        print(urlString)
        
        // 判断该字符串中是否包含code
        guard urlString.contains("code=") else {
            return true
        }
        
        // 将code截取出来
        let code = urlString.components(separatedBy: "code=").last!
        
        loadAccessToken(code: code)
        
        return false
    }
}

// MARK:- 根据code请求数据
extension OAuthViewController {
    // 请求AccessToken
    fileprivate func loadAccessToken(code : String) {
        NetworkTools.shareInstance.loadAccessToken(code: code) { (result, error) -> () in
            if error != nil {
                print(error!)
                return
            }
            
            guard let accountDict = result else {
                print("没有获取授权后的数据")
                return
            }
            
            let account = UserAccount(dict: accountDict)
            
            self.loadUserInfo(account: account)
        }
    }
    
    private func loadUserInfo(account : UserAccount) {
        guard let accessToken = account.access_token else {
            return
        }
        
        guard let uid = account.uid else {
            return
        }
        
        NetworkTools.shareInstance.loadUserInfo(access_token: accessToken, uid: uid) { (result, error) in
            if error != nil {
                print(error!)
                return
            }
            
            guard let userInfoDict = result else {
                return
            }
            
            account.screen_name = userInfoDict["screen_name"] as? String
            account.avatar_large = userInfoDict["avatar_large"] as? String
            
            // 将account对象保存到沙盒（归档）
            NSKeyedArchiver.archiveRootObject(account, toFile: UserAccountViewModel.shareIntance.accountPath)
            print(UserAccountViewModel.shareIntance.accountPath)
            
            // 把account对象设置到单例对象中
            UserAccountViewModel.shareIntance.account = account
            
            self.dismiss(animated: false, completion: {
                UIApplication.shared.keyWindow?.rootViewController = WelcomeViewController()
            })
        }
    }
}
